﻿using Hangfire.States;
using Hangfire.Storage;
using Hangfire;
using Hangfire.Common;
using System;
using System.Reflection;

namespace Hangfire_Demo.HFCustom
{
    public class CustomBackgroundJobStateChanger2 : IBackgroundJobStateChanger
    {
        private readonly IBackgroundJobStateChanger _inner;

        public void Apply(ApplyStateContext context, IWriteOnlyTransaction transaction)
        {
            // 获取作业执行结果
            var result = context.GetJobParameter<string>("result");

            if (result == "taskover")
            {
                // 将作业状态更改为成功
                ///context.NewState = new SucceededState();
                ///context.NewState.Reason = "Task completed successfully";
            }
            else if (result == "taskfault")
            {
                // 将作业状态更改为失败
                //context.NewState = new FailedState(new Exception("Task failed"));
            }

            // 应用默认的状态更改逻辑
            //context.State.Apply(context, transaction);
        }

        public void Unapply(ApplyStateContext context, IWriteOnlyTransaction transaction)
        {
            // 如果需要在取消状态更改时执行一些操作，可以在这里实现
            //context.State.Unapply(context, transaction);
        }

        public IState ChangeState(StateChangeContext context)
        {
            Console.WriteLine($"ChangeState {context.BackgroundJobId} to {context.NewState}");
            return _inner.ChangeState(context);
        }
    }
}
